package com.lqk.demo.atomic.atomicstampedreference;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

import static com.lqk.demo.n2.util.Sleeper.sleep;

/**
 * @author lqk
 * @date 2021/12/30 17:49
 */
@Slf4j
public class TestABAImprove {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A",0);

    public static void main(String[] args) throws InterruptedException {
        log.debug("main start...");
        // 获取值 A
        String prev = ref.getReference();
        // 获取版本号
        int stamp = ref.getStamp();
        log.debug("版本号:{}",stamp);
        // 如果中间有其它线程干扰，发生了 ABA 现象
        other();
        sleep(1);
        // 尝试改为 C
        log.debug("版本号:{}",stamp);
        log.debug("change A->C {}", ref.compareAndSet(prev, "C",stamp,stamp+1));
    }

    private static void other() {
        new Thread(() -> {
            int stamp = ref.getStamp();
            log.debug("版本号:{}",stamp);
            log.debug("change A->B {}", ref.compareAndSet(ref.getReference(), "B",stamp,stamp+1));
        }, "t1").start();
        sleep(0.5);
        new Thread(() -> {
            int stamp = ref.getStamp();
            log.debug("版本号:{}",stamp);
            log.debug("change B->A {}", ref.compareAndSet(ref.getReference(), "A",stamp,stamp+1));
        }, "t2").start();
    }
}
